import React, {Component} from 'react';

interface ErrorBoundaryProps {}
interface ErrorBoundaryState {
  hasError: boolean;
}

class ErrorBoundary extends Component<ErrorBoundaryProps, ErrorBoundaryState> {
  constructor(props: ErrorBoundaryProps) {
    super(props);
  }

  static getDerivedStateFromError(error: Error) {
    // 更新 state 使下一次渲染能够显示降级后的 UI
    console.log(error);
    return {hasError: true};
  }

  componentDidCatch(error: Error, errorInfo: React.ErrorInfo) {
    // 你同样可以将错误日志上报给服务器
    console.group();
    console.log('ErrorBoundary catch a error:');
    console.info('error', error);
    console.info('error info', errorInfo);
    console.groupEnd();
    global.showToast({
      title: error.message,
      icon: 'none',
    });
  }

  render() {
    const {children} = this.props;
    return children;
  }
}

export default ErrorBoundary;
